package com.zzwx.controller.dto;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDatePropertyEditor extends PropertyEditorSupport {
    String pattern;
    public MyDatePropertyEditor(){}
    public MyDatePropertyEditor(String pattern){
        this.pattern=pattern;
    }
    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getAsText() {
        SimpleDateFormat sf=new SimpleDateFormat(getPattern());
        Date value = (Date) getValue();
        if(null != value){
           return sf.format(value);
        }else{
            return null;
        }
    }

    public void setAsText(String text) throws IllegalArgumentException {
        Date date=null;
        SimpleDateFormat sf=new SimpleDateFormat(getPattern());
        if(text!=null&&!text.trim().equals("")){
            try {
                date=sf.parse(text);
            } catch (ParseException e) {
                try {
                    date=new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(text);
                } catch (ParseException e1) {
                    try {
                        date=new SimpleDateFormat("yyyy-MM-dd HH").parse(text);
                    } catch (ParseException e2) {
                        try {
                            date=new SimpleDateFormat("yyyy-MM-dd").parse(text);
                        } catch (Exception e3) {
                            setValue(date);
                        }
                    }
                }
            }
        }
        setValue(date);
    }

}
